<template>
  <div class="app-container">
    <!--    class="div-style"-->
    <div style="height: 45%;">
      <el-row style="height: 100%;">
        <el-col :span="5"
                style="background-color: #ffffff; height: calc(100% - 10px)">
          <div style="overflow: auto;height: 100%">
            <el-form ref="prescriptionFormRef" :model="prescriptionForm" :rules="prescriptionRules"
                     class="apply-form" label-width="85px">
              <el-form-item label="处方类型" prop="prescriptionType">
                <el-radio-group v-model="prescriptionForm.prescriptionType" :disabled="isDisabled  || isAdd"
                                class="prescriptionType-radio"
                                @change="prescriptionTypeChange">
                  <el-radio v-for="(dict, index) in dictDataMap['drug_classification']"
                            v-show="dict.dictLabel === '西药' || dict.dictLabel === '中草药'"
                            :key="dict.dictValue"
                            :value="dict.dictValue">{{
                      dict.dictLabel
                    }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="发药药房" prop="implementDept">
                <el-select v-model="prescriptionForm.implementDept" :disabled="isDisabled  || isAdd"
                           placeholder="请输入发药药房">
                  <el-option v-for="drugVsDept in drugVsDeptList" :key="drugVsDept.id"
                             :label="drugVsDept.storageName" :value="drugVsDept.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="处方属性" prop="prescAttr">
                <el-select v-model="prescriptionForm.prescAttr" :disabled="isDisabled  || isAdd"
                           placeholder="请选择处方属性">
                  <el-option v-for="dict in dictDataMap['prescription_type']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="prescriptionForm.prescriptionType === '2'" label="汤药名" prop="remarks">
                <el-input v-model="prescriptionForm.decoctionName" placeholder="请输入汤药名"
                />
              </el-form-item>
              <el-form-item label="处方备注" prop="remarks">
                <el-input v-model="prescriptionForm.remarks" :disabled="isDisabled  || isAdd"
                          maxlength="100"
                          type="textarea"
                          :autosize="{ minRows: 4, maxRows: 6 }"
                          placeholder="请输入处方备注信息"
                          show-word-limit/>
              </el-form-item>
              <el-form-item label="病种选择" prop="chargeType">
                <el-select v-model="prescriptionForm.diseaseInformation" :disabled="isDisabled" placeholder="请选择费别"
                           clearable>
                  <el-option v-for="dict in dictDataMap['disease_information_dict']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="2" style="background-color:#ffffff;">
          <div class="button-div"> <!--class="button-div"-->
            <el-button class="mb5 ml5" plain style="margin-left: 12px;margin-right: 8px;" type="primary"
                       @click="getListAndResetOk">
              <template #icon>
                <i-ep-search/>
              </template>
              刷新
            </el-button>
            <el-button class="mb5 ml5" plain style="margin-right: 8px;" type="primary" @click="resetPrescription">
              <template #icon>
                <i-ep-refresh/>
              </template>
              重置
            </el-button>
            <el-button :disabled="isDisabled && !prescriptionForm.applyId" class="mb5 ml5"
                       plain
                       style="margin-left: 12px;margin-right: 8px;"
                       type="primary" @click="handleAdd">
              <template #icon>
                <i-ep-plus/>
              </template>
              处方新增F1
            </el-button>
            <el-button v-if="!isOtcOutpatient" class="mb5 ml5" plain style="margin-right: 8px;" type="primary"
                       @click="historyClick">
              <svg-icon class="mr5" icon-class="history"/>
              历史
            </el-button>
            <el-button v-if="!isOtcOutpatient" class="mb5 ml5" color="#8888ff" plain style="margin-right: 8px;"
                       @click="templateOpen">
              <svg-icon class="mr5" icon-class="template"/>
              模板
            </el-button>
            <el-button class="mb5 ml5" color="#8888ff" plain style="margin-right: 8px;" @click="commonItemsClick">
              <template #icon>
                <i-ep-printer/>
              </template>
              常用项目
            </el-button>
            <el-button :disabled="!isDisabled" class="mb5 ml5" plain style="margin-right: 8px;" type="success"
                       @click="submitForm">
              <svg-icon class="mr5" icon-class="save"/>
              处方保存
            </el-button>
          </div>
        </el-col>
        <el-col :span="17">
          <el-table :border="true" :data="prescriptionApplyList" :header-cell-style="$headerCellStyle" :stripe="true"
                    height="calc(100% - 34px)" highlight-current-row @row-click="rowClick">
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                             width="90"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方属性" prop="prescAttr"
                             width="80">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['prescription_type']"
                               :value="scope.row.prescAttr"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方分类" prop="itemClass"
                             width="70">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['bill_item_class_dict']"
                               :value="scope.row.itemClass"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申请序号" prop="applyNo"
                             width="100"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="开单科室" prop="applyDeptName"
                             width="90"/>
            <el-table-column :align="'center'" label="开单时间" prop="createTime" width="130"/>
            <el-table-column :align="'left'" :show-overflow-tooltip="true" header-align="center" label="发药药房"
                             prop="implementDeptName"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="发药标志" prop="confirmFlag"
                             width="90">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['grant_flag']" :value="scope.row.confirmFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="收费标志" prop="chargeFlag"
                             width="135">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['charge_flag_dict']"
                               :value="scope.row.chargeFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="发药执行人" prop="implementUserName" width="90"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="发药时间" prop="grantTime"
                             width="130">
              <template #default="scope">
                <span>{{ $parseTime(scope.row.grantTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注信息"
                             prop="remarks" width="100"/>
            <el-table-column :align="'center'" label="确认退药人" prop="returnDrugUser" width="90"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="确认退药时间"
                             prop="returnDrugTime"
                             width="130">
              <template #default="scope">
                <span>{{ $parseTime(scope.row.returnDrugTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'left'" class-name="small-padding fixed-width" fixed="right"
                             label="操作"
                             width="120">
              <template #default="scope">
                <el-tooltip class="item" content="打印" effect="dark" placement="top">
                  <el-button circle type="primary" @click="prescPrint(scope.row)">
                    <template #icon>
                      <i-ep-printer/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.isAtomization === '1'" class="item" content="雾化单打印"
                            effect="dark"
                            placement="top">
                  <el-button circle type="warning" @click="atomizationPrint(scope.row)">
                    <template #icon>
                      <i-ep-printer/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.isInfusion === '1'" class="item" content="输液单打印"
                            effect="dark"
                            placement="top">
                  <el-button circle type="success" @click="infusionPrint(scope.row)">
                    <template #icon>
                      <i-ep-printer/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.chargeFlag === '1'" class="item" content="删除"
                            effect="dark"
                            placement="top">
                  <el-button circle type="danger" @click="handleDelete(scope.row)">
                    <template #icon>
                      <i-ep-delete/>
                    </template>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                      @pagination="getList"/>
        </el-col>
        <!-- <el-col :span="3" style="background-color:
#ffffff;height: calc(100% + 28px)"> -->
      </el-row>

    </div>
    <div style="height: 55%">
      <template v-if="westOrChinese">
        <western-medicine ref="prescriptionItemRef" :apply-is-disabled="isDisabled" :is-otc-outpatient="isOtcOutpatient"
                          :org-id="userInfo.orgId" @submit-ok="submitOk" @item-submit-ok="itemSubmitOk"/>
      </template>
      <template v-else>
        <chinese-medicine ref="chineseMedicineRef" :apply-is-disabled="isDisabled" :org-id="userInfo.orgId"
                          @submit-ok="submitOk" @item-submit-ok="itemSubmitOk"/>
      </template>
    </div>

    <!-- 精麻毒类处方、诊断列表弹出框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="45%"
               @close="cancel">
      <el-divider content-position="left"><span class="divider-css">诊断信息</span></el-divider>
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="diagnosisList">
          <el-table ref="hisDiagnosisRef" :border="true" :data="hisDiagnosisList" style="margin-bottom: 28px"
                    :header-cell-style="$headerCellStyle" :stripe="true" highlight-current-row
                    @select="hisDiagnosisSelectionChange" @select-all="selectAll">
            <el-table-column :align="'center'" type="selection" width="40"/>
            <el-table-column :align="'center'" label="西/中医诊断" prop="type">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['chinese_western_type']" :value="scope.row.type"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="诊断类型" prop="diagnosisType" width="110px">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['diagnosis_type']"
                               :value="scope.row.diagnosisType"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                             width="150px"/>
            <el-table-column :align="'center'" label="诊断编码" prop="icdCode"/>
            <!--            <el-table-column :align="'center'" label="效果" prop="effect">-->
            <!--              <template #default="scope">-->
            <!--                <dict-data-tag :options="dictDataMap['treatment_type']" :value="scope.row.effect"/>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column :align="'center'" label="诊断医生" prop="diagnosisDoctorName" width="100"/>
          </el-table>
        </el-form-item>
        <template v-if="prescriptionForm.prescAttr === '3' || prescriptionForm.prescAttr === '4'
                    || prescriptionForm.prescAttr === '7'">
          <el-divider content-position="left"><span class="divider-css">人员信息</span></el-divider>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="是否本人">
                <el-select v-model="dialogForm.agency" style="width: 100%" @change="agencyChange">
                  <el-option key="1" label="代办人" value="1"/>
                  <el-option key="2" label="本人" value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="dialogForm.agency === '1' ? '代办人姓名' : '本人姓名'"
                            prop="agencyBy">
                <el-input v-model="dialogForm.agencyBy"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="dialogForm.agency === '1' ? '代办人年龄' : '本人年龄'"
                            prop="agencyAge">
                <el-input v-model="dialogForm.agencyAge"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="dialogForm.agency === '1' ? '代办人性别' : '本人性别'"
                            prop="agencySex">
                <el-select v-model="dialogForm.agencySex">
                  <el-option v-for="dict in dictDataMap['sys_user_sex']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item :label="dialogForm.agency === '1' ? '代办人身份证' : '本人身份证'" prop="agencyNo">
            <el-input v-model="dialogForm.agencyNo"/>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="dialogOk">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>

    <!-- 历史、常用项目、模板弹出框 -->
    <el-dialog v-model="historyOpen" :close-on-click-modal="false" :title="historyTitle" append-to-body width="90%"
               @close="historyCancel">
      <!-- 历史 -->
      <history v-if="historyType === 1" :inorout-flag="inoroutFlag" :org-id="userInfo.orgId"
               :patient-id="patientId" :refresh-key="historyKey" @apply-quote="historyApplyQuote"/>
      <template-quote v-else-if="historyType === 3" ref="templateQuoteRef" :query-params="templateParams"
                      :refresh-key="historyKey" @quote-ok-index="quoteOkIndex"/>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {useDictStoreHook} from "@/store/modules/dict";
import {
  delPrescriptionApply,
  getPrescriptionApply,
  refundApplication,
  saveTemplateApply,
  selectPagePrescriptionApply
} from "@/api/patient/prescriptionApply.ts";
import {listHisDiagnosis} from "@/api/diagnosis/hisDiagnosis.ts";
import {useUserStoreHook} from "@/store/modules/user";
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts"
import westernMedicine from "./westernMedicine.vue"
import ChineseMedicine from "@/views/doctor/prescription/chineseMedicine.vue";
import templateQuote from "./template/templateQuote.vue"
import {idNo} from "@/utils/myRules.ts"
import history from './history.vue';
import {selectConfigByCache} from "@/api/system/orgConfig.ts";

const dictStore = useDictStoreHook();
const {proxy} = getCurrentInstance() as any;
const templateQuoteRef = ref()
// 患者门诊信息
const clinicInfo = ref<any>(proxy.$clinicInfo)

const formRef = ref();
// 左上方处方主信息form
const prescriptionFormRef = ref();
// 西药或中药：true 西药 ； false 中药
const westOrChinese = ref<boolean>(true)
// 药房list
const drugVsDeptList = ref<any>([])
const westernDrugList = ref<any>([])
const chineseDrugList = ref<any>([])
const title = ref<string>("信息选择")
// 历史、常用项目、模板弹出框 标题
const historyTitle = ref<string>("")
const open = ref<boolean>(false)
// 、模板弹出框 关闭打开状态
const historyOpen = ref<boolean>(false)
// 历史、常用项目、模板弹出框 内容状态 1：历史 2：常用项目 3：模板
const historyType = ref<number>(1)
const total = ref(0);
// 诊断列表
const ids = ref([""]);
const hisDiagnosisRef = ref()
// 诊断列表
const hisDiagnosisList = ref<any>([])
const historyKey = ref<number>(0)
// 西药明细组件
const prescriptionItemRef = ref()
// 中药明细组件
const chineseMedicineRef = ref()
// 处方主信息是否禁用
const isDisabled = ref<boolean>(false)
// 是否点击新增按钮
const isAdd = ref<boolean>(false)

//便捷门诊可以不选诊断开药
const diagnosisIsEmpty = ref("N")
const objectUrl = ref("")
let dictDataMap = ref(dictStore.isTypeGetData('prescription_type', 'drug_classification', 'bill_item_class_dict',
  'charge_flag_dict', 'grant_flag', 'sys_user_sex', 'diagnosis_type', 'chinese_western_type', 'disease_information_dict'))
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const prescriptionApplyList = ref([]);
const clinicId = ref(proxy.$clinicId);
const patientId = ref(proxy.$patientId);
const visitId = ref("")
const props = defineProps({
  inoroutFlag: {
    type: String,
    default: ""
  },
  // 是否来自便捷门诊，用于判断开处方是否可以不开诊断
  isToConvenientOutpatient: {
    type: Boolean,
    default: false
  },
  // 是否来在OTC门诊   ，用于判断只能开otc药品
  isOtcOutpatient: {
    type: Boolean,
    default: true
  }
});
const queryParams = ref<any>({
  orgId: userInfo.orgId,
  clinicId: clinicId.value,
  patientId: patientId.value,
  inoroutFlag: props.inoroutFlag
});
// 左上方处方主信息form
const prescriptionForm = ref<any>({
  prescriptionType: '1',
  diseaseInformation: '',
  clinicId: clinicId.value,
  visitId: "",
  patientId: patientId.value,
  inoroutFlag: props.inoroutFlag,
  implementDept: "",
  prescAttr: "1",
  drugClass: "A",
  applyDept: userInfo.loginDeptId,
  applyUser: userInfo.userId,
  prescriptionItemBoList: [],
  orgId: userInfo.orgId,
  hisDiagnosisList: {}
})
const templateParams = ref<TemplateMasterType>({
  pageNum: 1,
  pageSize: 10,
  type: "0",
  authorityType: userInfo.customerType != '3' ? '' : "0",
  title: "",
  titleInput: "",
  deptId: userInfo.loginDeptId,
  orgId: userInfo.orgId,
  storageId: prescriptionForm.value.implementDept,
  // 用于加载模板子页面区分加载中药、西药
  showItemClass: prescriptionForm.value.prescriptionType === '1' ? "A" : "B"
})
const prescriptionRules = ref<any>({
  implementDept: [
    {
      required: true, message: "发药药房不能为空", trigger: "blur"
    }
  ],
  prescriptionType: [
    {
      required: true, message: "处方类型不能为空", trigger: "blur"
    }
  ],
  prescAttr: [
    {
      required: true, message: "处方属性不能为空", trigger: "change"
    }
  ],
})
const dialogFormRef = ref()
const dialogForm = ref<any>({
  // 1代办  2本人
  agency: "1",
  agencyBy: '',
  agencyNo: '',
  agencyAge: '',
  agencySex: '',
  diagnosisList: ''
})
const dialogRules = ref<any>({
    diagnosisList: [
      {required: true, message: "请先开具诊断或者选择至少一条诊断后，再保存", trigger: "change"}
    ],
    agencyBy: [
      {required: true, message: "代办人不能为空", trigger: "blur"}
    ],
    agencyNo: [
      {required: true, validator: idNo, trigger: "blur"}
    ],
    agencyAge: [
      {required: true, message: "代办人年龄不能为空", trigger: "blur"}
    ],
    agencySex: [
      {required: true, message: "代办人性别不能为空", trigger: "blur"}
    ]
  }
)

// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: userInfo.loginDeptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("4,2,0", ","),
    storageTypeArray: proxy.$stringToArray("2,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("1", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    drugVsDeptList.value = res.data
    westernDrugList.value = res.data.filter((item: any) => {
      return item.storageClass !== "1"
    })
    chineseDrugList.value = res.data.filter((item: any) => {
      return item.storageClass !== "2"
    })
    prescriptionTypeChange()
  })
}


function selectAll() {
  hisDiagnosisRef.value.clearSelection()
}

const drugClassArrayParent = ref<any>([])

// 定义西药和中药的配置类型
interface PrescriptionConfig {
  drugVsDeptList: any[];
  drugClass: string;
  defaultPrescAttr: string;
  storageName: string;
  ref: any;
}

/**
 * 根据药房列表和目标药房名称获取对应的存储编码
 * @param drugVsDeptList - 包含药房信息的数组，每个元素是一个对象，应包含 storageName 和 storageCode 属性
 * @param storageName - 目标药房的名称
 * @returns 如果找到匹配的药房名称，返回对应的存储编码；若未找到，返回列表中第一个药房的存储编码
 */
function getStorageCode(drugVsDeptList: any[], storageName: string) {
  // 在 drugVsDeptList 中查找 storageName 等于目标名称的元素，返回其索引
  const index = drugVsDeptList.findIndex((item: any) => item.storageName === storageName);
  // 如果找到了匹配的元素，返回该元素的 storageCode；否则返回列表中第一个元素的 storageCode
  return index > -1 ? drugVsDeptList[index].storageCode : drugVsDeptList[0].storageCode;
}

/**
 * 根据药房列表和特定值生成药品类别数组
 * @param drugVsDeptList - 包含药房信息的数组，数组中第一个元素需有 drugClass 属性，该属性为逗号分隔的字符串
 * @param includeValue - 可选参数，若存在则只保留数组中等于该值的元素；若为 null 则排除值为 '2' 的元素
 * @returns 处理后的药品类别数组
 */
function setDrugClassArray(drugVsDeptList: any[], includeValue: string | null) {
  // 从药房列表的第一个元素中获取 drugClass 属性，并按逗号分割成数组
  const drugClassArray = drugVsDeptList[0].drugClass.split(",");
  // 判断分割后的数组是否为空字符串，若为空则返回空数组，否则根据 includeValue 进行过滤
  return drugClassArray === "" ? [] : drugClassArray.filter(item =>
    includeValue ? item === includeValue : item !== '2'
  );
}

/**
 * 处方类型改变时的处理函数，根据处方类型切换西药或中药的相关配置
 */
function prescriptionTypeChange() {
  // 定义西药的配置对象
  const westernConfig: PrescriptionConfig = {
    drugVsDeptList: westernDrugList.value, // 西药药房列表
    drugClass: "A", // 西药药品类别
    defaultPrescAttr: "1", // 西药默认处方属性
    storageName: "西药房", // 西药对应的药房名称
    ref: prescriptionItemRef.value // 西药明细组件引用
  };

  // 定义中药的配置对象
  const chineseConfig: PrescriptionConfig = {
    drugVsDeptList: chineseDrugList.value, // 中药药房列表
    drugClass: "B", // 中药药品类别
    defaultPrescAttr: "2", // 中药默认处方属性
    storageName: "中药房", // 中药对应的药房名称
    ref: chineseMedicineRef.value // 中药明细组件引用
  };
  // 根据当前处方类型选择对应的配置对象
  const config = prescriptionForm.value.prescriptionType === "1" ? westernConfig : chineseConfig;

  // 更新药房列表
  drugVsDeptList.value = config.drugVsDeptList;
  // 更新当前是西药还是中药的标识
  westOrChinese.value = prescriptionForm.value.prescriptionType === "1";
  // 更新处方的药品类别
  prescriptionForm.value.drugClass = config.drugClass;
  // 根据配置获取并更新发药药房编码
  prescriptionForm.value.implementDept = getStorageCode(config.drugVsDeptList, config.storageName);

  // 如果处方属性为空，则设置为默认值
  if (!prescriptionForm.value.prescAttr) {
    prescriptionForm.value.prescAttr = config.defaultPrescAttr;
  }

  // 根据处方类型确定是否只包含值为 '2' 的项
  const includeValue = prescriptionForm.value.prescriptionType === "2" ? '2' : null;
  // 生成药品类别数组
  const drugClassArray = setDrugClassArray(config.drugVsDeptList, includeValue);
  // 更新父组件的药品类别数组
  drugClassArrayParent.value = drugClassArray;

  // 如果是中药处方，将 '2' 添加到药品类别数组中
  if (prescriptionForm.value.prescriptionType === "2") {
    drugClassArray.push("2");
  }

  // 在下一个 DOM 更新周期触发时，调用对应组件的方法设置药品类别数组和发药药房编码
  nextTick(() => {
    if (config.ref && typeof config.ref.setDrugClassArray === 'function') {
      config.ref.setDrugClassArray(drugClassArray, prescriptionForm.value.implementDept);
    }
  });
}

function reset() {
}

function getListAndResetOk() {
  resetOk()
  getList()
}

/** 查询处方主表列表 */
function getList() {
  selectPagePrescriptionApply(queryParams.value).then((response: any) => {
    prescriptionApplyList.value = response.rows;
    total.value = response.total;
  });
}


// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('keydown',
    handleKeydown);
});
// 组件卸载时移除事件监听以避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('keydown',
    handleKeydown);
});

function handleKeydown(event) {
  if (event.keyCode == "112") {
    event.preventDefault();//阻止浏览器默认事件
    handleAdd()
  }
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构")
  }
  if (isDisabled.value && !prescriptionForm.value.applyId) {
    return ElMessage.error("处方信息已选择，不能再次新增。")
  }
  if (prescriptionForm.value.applyId) {
    ElMessageBox.confirm('点击新增处方操作，当前处方将会被重置，确定要进行删除操作吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      resetOk()
      addOk()
    }).catch(() => {
      ElMessage.info("操作终止")
    })
  } else {
    addOk()
  }
}

function addOk() {
  (prescriptionFormRef.value as any).validate(valid => {
    if (valid) {
      reset();
      isDisabled.value = true
      isAdd.value = true
      if (prescriptionForm.value.prescriptionType === "1") {
        nextTick(() => {
          prescriptionItemRef.value.setDrugClassArray(drugClassArrayParent.value, prescriptionForm.value.implementDept)
          prescriptionItemRef.value.parentHandleAddDrug()
        })
      } else {
        chineseMedicineRef.value.setDrugClassArray(drugClassArrayParent.value, prescriptionForm.value.implementDept)
        chineseMedicineRef.value.handleAddDrug()
      }

    }
  })
}

// 处方主信息重置
function resetPrescription() {
  ElMessageBox.confirm('重置后未保存的数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    resetOk()
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

// 历史按钮点击事件
function historyClick() {
  // 强制刷新弹出框内容
  historyKey.value = historyKey.value + 1
  historyTitle.value = "历史处方"
  historyOpen.value = true
  historyType.value = 1

}

// 模板按钮点击事件
function templateOpen() {
  // 强制刷新弹出框内容
  historyKey.value = historyKey.value + 1
  historyTitle.value = "模板"
  historyOpen.value = true
  historyType.value = 3
  templateParams.value.storageId = prescriptionForm.value.implementDept
  templateParams.value.showItemClass = prescriptionForm.value.prescriptionType === '1' ? "A" : "B"
}

// 常用项目按钮点击事件
function commonItemsClick() {
  historyTitle.value = "常用项目"
  historyOpen.value = true
  historyType.value = 2
}

function resetOk() {
  isDisabled.value = false
  isAdd.value = false
  prescriptionForm.value.prescAttr = "1"
  prescriptionForm.value.remarks = ""
  prescriptionForm.value.diseaseInformation = ""
  prescriptionForm.value.clinicId = clinicId.value
  prescriptionForm.value.visitId = ""
  prescriptionForm.value.patientId = patientId.value
  prescriptionForm.value.inoroutFlag = props.inoroutFlag
  prescriptionForm.value.implementDept = ""
  prescriptionForm.value.drugClass = prescriptionForm.value.prescriptionType === '1' ? "A" : "B"
  prescriptionForm.value.applyDept = userInfo.loginDeptId
  prescriptionForm.value.applyUser = userInfo.userId
  prescriptionForm.value.prescriptionItemBoList = []
  prescriptionForm.value.orgId = userInfo.orgId
  prescriptionForm.value.hisDiagnosisList = {}
  prescriptionForm.value.applyId = ""
  prescriptionTypeChange()
  if (prescriptionForm.value.prescriptionType === "1") {
    prescriptionItemRef.value.emptyDrugList(false)
  } else {
    chineseMedicineRef.value.emptyDrugList(false)
  }
}

/**
 * 诊断单选
 * @param selection
 */
function hisDiagnosisSelectionChange(selection: any) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    hisDiagnosisRef.value.toggleRowSelection(del_row, false);
  }
  ids.value = selection.map(item => item.id);
  const index = hisDiagnosisList.value.findIndex(item => {
    return item.id === ids.value[0]
  })
  if (index > -1) {
    dialogForm.value.diagnosisList = hisDiagnosisList.value[index]
  }

}

/**
 * 对明细进行校验
 */
function submitForm() {
  if (prescriptionForm.value.applyId) {
    getPrescriptionApply(prescriptionForm.value.applyId).then((res: resType) => {
      const data: any = res.data
      if (data.chargeFlag === '1') {
        itemValidate()
      } else {
        ElMessage.error("本条处方已收费，不能进行保存操作。")
      }
    })
  } else {
    itemValidate()
  }
}

/**
 * 明细校验
 */
function itemValidate() {
  if (prescriptionForm.value.prescriptionType === "1") {
    prescriptionItemRef.value.itemValidate()
  } else {
    chineseMedicineRef.value.itemValidate()
  }
}

/**
 * 通过orgId key获取对应的机构参
 */
function selectConfigByCacheFun() {
  // 便捷门诊可以不选诊断开药
  selectConfigByCache(userInfo.orgId, "convenientOutpatient.diagnosis.isEmpty").then((res => {
    diagnosisIsEmpty.value = res.data.configValue
  }))
}

/**
 * 检验通过，弹出诊断选择狂
 * 校验通过后，由处方明细组件emits调用
 */
function openTrue() {
  open.value = true
  if (dialogForm.value.agency === "2") {
    dialogForm.value.agencyBy = clinicInfo.value.name
    dialogForm.value.agencyNo = clinicInfo.value.idNo
    dialogForm.value.agencyAge = clinicInfo.value.age
    dialogForm.value.agencySex = clinicInfo.value.sex
  }
  hisDiagnosisList.value.forEach((item: any) => {
    nextTick(() => {
      hisDiagnosisRef.value.toggleRowSelection(item, false);
    })
  })
  const index = hisDiagnosisList.value.findIndex((item: any) => {
    return item.id === ids.value[0]
  })
  if (index > -1) {
    nextTick(() => {
      //让页面显示选中的数据
      hisDiagnosisRef.value.toggleRowSelection(hisDiagnosisList.value[index], true);
    })
  }
}

// 判断是否来自便捷门诊 并且弹诊断选择框
function itemSubmit() {
  // 不是来自便捷门诊，默认必须都掉诊断
  if (!props.isToConvenientOutpatient) {
    openTrue()
  } else {
    //  来自便捷门诊
    // 并且 便捷门诊必须选诊断开药
    if (diagnosisIsEmpty.value === 'N') {
      openTrue()
    } else {
      // 便捷门诊可以不选诊断开药
      saveIsOk()
    }
  }
}

function agencyChange() {
  if (dialogForm.value.agency === "2") {
    dialogForm.value.agencyBy = clinicInfo.value.name
    dialogForm.value.agencyNo = clinicInfo.value.idNo
    dialogForm.value.agencyAge = clinicInfo.value.age + "岁" + clinicInfo.value.ageMonth + "月" + clinicInfo.value.ageDay + "天"
    dialogForm.value.agencySex = clinicInfo.value.sex
  } else {
    dialogForm.value.agencyBy = ""
    dialogForm.value.agencyNo = ""
    dialogForm.value.agencyAge = ""
    dialogForm.value.agencySex = ""
  }
}

/**
 * 是否确认保存
 */
function saveIsOk() {
  if (prescriptionForm.value.prescriptionType === "1") {
    prescriptionItemRef.value.saveIsOk(prescriptionForm.value)
  } else {
    chineseMedicineRef.value.saveIsOk(prescriptionForm.value)
  }
}

function itemSubmitOk() {
  itemSubmit()
}

/**
 * 最终保存方法的父页面调用，处理后续逻辑
 */
function submitOk() {
  getList()
  resetOk()
  dialogForm.value.diagnosisList = []
  ids.value = []
  open.value = false
}

/**
 * 右侧列表点击事件
 */
function rowClick(row: any) {
  getPrescriptionApply(row.applyId).then((res: resType) => {
    const data: any = res.data
    prescriptionForm.value = {
      prescriptionType: data.itemClass === "A" ? "1" : "2",
      clinicId: data.clinicId,
      diseaseInformation: data.diseaseInformation,
      visitId: data.visitId,
      patientId: data.patientId,
      inoroutFlag: data.inoroutFlag,
      implementDept: data.implementDept,
      prescAttr: data.prescAttr,
      drugClass: data.drugClass,
      applyDept: data.applyDept,
      applyUser: data.applyUser,
      remarks: data.remarks,
      orgId: data.orgId,
      applyId: data.applyId,
      diagnosis: data.diagnosis,
      drugInfoId: data.drugInfoId,
      icdName: data.icdName,
      icdCode: data.icdCode,
      diagnosisId: data.diagnosisId,
      decoctionName: data.decoctionName
    }
    ids.value = []
    ids.value.push(data.diagnosisId)
    const index = hisDiagnosisList.value.findIndex(item => {
      return item.id === ids.value[0]
    })
    if (index > -1) {
      dialogForm.value.diagnosisList = hisDiagnosisList.value[index]
    }
    isDisabled.value = data.chargeFlag == '1';
    isAdd.value = data.chargeFlag == '1';
    prescriptionTypeChange()
    applyRowClickFun(data)
  })
}


/**
 * 删除处方信息
 * @param row
 */
function handleDelete(row: any) {
  ElMessageBox.confirm('删除后数据将丢失，确定要进行删除操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delPrescriptionApply(row.applyId).then(() => {
      getList()
      resetOk()
      ElMessage.success("删除成功")
    })
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/**
 * 处方打印
 * @param row
 */
function prescPrint(row: any) {
  let url = "/business/prescriptionApply/prescPrint";
  const formData = new FormData()
  formData.append("applyId", row.applyId)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('处方打印失败')
    }
  })
}

/**
 * 雾化单打印
 * @param row
 */
function atomizationPrint(row: any) {
  let url = "/business/prescriptionApply/atomizationPrint";
  const formData = new FormData()
  formData.append("applyId", row.applyId)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('雾化单打印失败')
    }
  })
}

/**
 * 关闭弹出框
 */
function cancel() {
  open.value = false
}

/**
 * 关闭历史、常用项目、模板弹出框
 */
function historyCancel() {
  // 清空模板明细信息
  if (historyType.value === 3) {
    nextTick(() => {
      templateQuoteRef.value.emptyPrescriptionItemList()
    })
  }
  historyOpen.value = false
}

/** 查询患者诊断表列表 */
function getDiagnosisList() {
  const form = {
    patientId: patientId.value,
    clinicId: clinicId.value
  }
  listHisDiagnosis(form).then((response: any) => {
    hisDiagnosisList.value = response.data;
  });
}

/**
 * 弹出框确认按钮
 */
function dialogOk() {
  (dialogFormRef.value as any).validate(valid => {
    if (valid) {
      prescriptionForm.value.agency = dialogForm.value.agency
      prescriptionForm.value.agencyAge = dialogForm.value.agencyAge
      prescriptionForm.value.agencyBy = dialogForm.value.agencyBy
      prescriptionForm.value.agencyNo = dialogForm.value.agencyNo
      prescriptionForm.value.agencySex = dialogForm.value.agencySex
      prescriptionForm.value.diagnosisList = dialogForm.value.diagnosisList
      saveIsOk()
    }
  })
}

/**
 * 历史处方引用事件
 */
function historyApplyQuote(obj: any) {
  const apply = obj
  apply.historyApplyQuote = true
  prescriptionForm.value.prescriptionType = apply.itemClass === "A" ? "1" : "2"
  prescriptionForm.value.clinicId = clinicId.value
  prescriptionForm.value.visitId = visitId.value
  prescriptionForm.value.patientId = patientId.value
  prescriptionForm.value.inoroutFlag = apply.inoroutFlag
  prescriptionForm.value.prescAttr = apply.prescAttr
  prescriptionForm.value.drugClass = apply.drugClass
  prescriptionForm.value.orgId = apply.orgId
  // 历史引用的处方 收费状态默认为 未收费
  prescriptionForm.value.chargeFlag = "1"
  prescriptionForm.value.applyDeptorgId = userInfo.loginDeptId
  prescriptionForm.value.createTime = undefined
  prescriptionForm.value.createBy = ""
  prescriptionForm.value.createByName = ""
  prescriptionForm.value.updateTime = undefined
  prescriptionForm.value.updateBy = ""
  prescriptionForm.value.updateByName = ""
  isDisabled.value = true
  isAdd.value = true
  prescriptionTypeChange()
  if (prescriptionForm.value.prescriptionType === "1") {
    nextTick(() => {
      prescriptionItemRef.value.historyApplyQuoteFun(apply)
    })
  } else {
    nextTick(() => {
      chineseMedicineRef.value.historyApplyQuoteFun(apply)
    })
  }
  historyCancel()
}

/**
 * 处方主记录点击事件、明细加载事件
 * @param data  prescription_apply 信息 主要要有applyId
 */
function applyRowClickFun(data: any) {
  if (prescriptionForm.value.prescriptionType === "1") {
    nextTick(() => {
      prescriptionItemRef.value.applyRowClick(data)
    })
  } else {
    nextTick(() => {
      chineseMedicineRef.value.applyRowClick(data)
    })
  }
}


/** 申请退费 */
function refundApplicationFun(row, chargeFlag) {
  let message = "确认要进行申请退费？";
  if (chargeFlag === "2") {
    // 撤销退费
    message = "确认要进行撤销退费操作吗？";
  }
  ElMessageBox.confirm(message,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    refundApplication(row.applyId, chargeFlag).then((res: any) => {
      if (res.data) {
        if (chargeFlag === "2") {
          ElMessage.success("撤销退费成功。")
        } else if (chargeFlag === "3") {
          ElMessage.success("申请退费成功。")
        }
      } else {
        if (chargeFlag === "2") {
          ElMessage.success("撤销退费失败。")
        } else if (chargeFlag === "3") {
          ElMessage.error("申请退费失败。");
        }
      }
      getList()
    })
  })
}

/**
 * 输液单打印
 * @param row
 */
function infusionPrint(row: any) {
  let url = "/business/prescriptionApply/infusionPrint";
  const formData = new FormData()
  formData.append("applyId", row.applyId)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('输液打印失败')
    }
  })
}

/***********************************  模板引用  **********************************/
function quoteOkIndex(list: any) {
  list.forEach((item: any) => {
    item.drugCode = item.drugCode || item.itemCode
    item.chargeFlag = '1'
    item.confirmFlag = '1'
    item.repetition = 1
    item.prescAttr = prescriptionForm.value.prescAttr

  })
  const data = {
    "drugClass": prescriptionForm.value.prescriptionType === '1' ? "A" : "B",
    "templateList": list,
    "clinicId": clinicId.value,
    "visitId": visitId.value,
    "patientId": patientId.value,
    "applyDept": userInfo.loginDeptId,
    "applyUser": userInfo.userId,
    "inoroutFlag": props.inoroutFlag,
    "orgId": userInfo.orgId,
    "chargeFlag": "1",
    "applyDeptorgId": userInfo.loginDeptId,
    "repetition": 1,
    "implementDept": prescriptionForm.value.implementDept,
  }
  nextTick(() => {
    saveTemplateApply(data).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success("保存成功")
        getListAndResetOk()
        isDisabled.value = false
        isAdd.value = true
        historyCancel()
      } else {
        ElMessage.error(res.msg)
      }
    })
    // prescriptionItemRef.value.templateQuote(list)
  })
}

getList();
getDrugVsDeptListFun()
getDiagnosisList()
selectConfigByCacheFun()
defineExpose({
  getList
})
</script>

<style scoped>
.app-container {
  padding: 5px;
}

:deep(.el-dialog__header) {
  margin-bottom: -40px !important;
}


.button-div {
  /** 将按钮容器设置为Flexbox布局。 **/
  display: flex;
  /** 将按钮容器的子元素垂直排列。 **/
  flex-direction: column;
  /** 将按钮容器的子元素在垂直方向上居中对齐。 **/
  /* align-items: center; */
  /** 将按钮容器的子元素在垂直方向上平均分布，实现等间距效果。 **/
  justify-content: space-between;
}

.button-div > button {
  border: 1px solid #4E64F6;
  background: #fff;
  border-radius: 17px;
  height: 34px;
  color: #4E64F6;
}

.button-div > button:hover {
  background: #4E64F6;
  color: #fff;
}

:deep(.prescriptionType-radio.el-radio-group) {
  display: inline-flex;
  align-items: center;
  flex-wrap: nowrap;
  font-size: 0;
}

:deep(.apply-form.el-form) {
  margin-left: -15px;
}

:deep(.apply-form.el-form) {
  padding-right: 16px;
}

/*.el-table--fit {
  height: calc(100% - 24px) !important;
}*/

:deep(.el-divider--horizontal) {
  margin: 30px 0 10px 0 !important;;
}


:deep(.el-table__header-wrapper .el-checkbox__inner) {
  display: none;
}

/*:deep(.el-table__inner-wrapper) {
  height: 280px !important;
}*/
</style>
